package com.qf.kk.servlet;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/*
 *@author KK on 2022.09.14 13:35
 */
@WebServlet("/download")
public class dowdload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要下载的文件所在路径
        String realPath = req.getServletContext().getRealPath("/upload");
        //设置文件名，获取到文件路径
        String fileName = "ha.txt";
        String filePath = realPath + "\\" + fileName;
        //使用本地流读取文件
        InputStream inputStream = new FileInputStream(filePath);
        //使用url进行中文的编码处理，浏览器下载时会自动解码转成中文
        String encode = URLEncoder.encode("C:\\Users\\KK\\Desktop\\ha.txt", "utf-8");
        //写出文件之前设置响应头
        resp.setHeader("Content-disposition","attachment;filename="+encode);
        OutputStream outputStream = resp.getOutputStream();
        byte[] bytes = new byte[1024];
        int i;
        while ((i=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,i);
        }
        outputStream.close();
        inputStream.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
